import Headnav from "./index.module.less";
import { SearchOutlined, CloudOutlined, BellOutlined } from "@ant-design/icons";
import { Form, Dropdown, Menu, Space, message } from "antd";
import "./model.less";
import { NavLink, useLocation, useNavigate } from "react-router-dom";
import { useState, useEffect, useCallback } from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
// import { rootState } from "@/store";
import { usertype } from "@/store/reducers/home";
import {
  changethemeinessay,
  getcollectidar1,
  loginpatch,
} from "@/store/action/home";
import { rootState } from "@/store";

import Loginmodel from "../Login";
import Registermodel from "../Register";
import { getnotreadycountapi } from "@/apis/essay";

export default function HeadNav() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  //注册表单，方便重置数据
  const [registerform] = Form.useForm();
  //登录表单，方便重置数据
  const [loginform] = Form.useForm();
  const [ani, setAni] = useState<boolean>(false);
  //登录注册对话框是否显示
  const [loginvisiable, setLogininvisiable] = useState<boolean>(false);
  const [registevisiable, setRegistervisiable] = useState<boolean>(false);

  const [notreadycount, setNotreadycount] = useState<number>(0); //没有读取的消息的数量

  //用户信息
  const { user, essaypretheme } = useSelector(
    (store: rootState) => ({
      user: store.home.user as usertype,
      essaypretheme: store.home.essaypretheme,
    }),
    shallowEqual
  );

  useEffect(() => {
    let curtop = 0;
    //节流
    window.addEventListener("scroll", () => {
      if (document.documentElement.scrollTop > 0) {
        if (document.documentElement.scrollTop > curtop) {
          setAni(true);
        } else {
          setAni(false);
        }
        curtop = document.documentElement.scrollTop;
      }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  //建立websocket连接
  useEffect(() => {
    const ws = new WebSocket(`ws://localhost:8000/ws/changestatenotice?myid=2`);
    ws.addEventListener("message", (data) => {
      getnotreadycountfn();
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  //路由改变时获取消息数量
  useEffect(() => {
    if (location.pathname !== "/Notice" && user.id) {
      getnotreadycountfn();
    }
    if (location.pathname === "/Notice") {
      setNotreadycount(0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);
  //切换主题
  const changetheme = () => {
    if (essaypretheme === "light") {
      dispatch(changethemeinessay("dark"));
    } else {
      dispatch(changethemeinessay("light"));
    }
  };
  //关闭登录对话框，打开注册对话框
  const toregistermodel = useCallback(() => {
    loginform.resetFields();
    setLogininvisiable(false);
    setRegistervisiable(true);
  }, [loginform]);
  //关闭注册对话框，打开登录对话框
  const tologinmodel = useCallback(() => {
    registerform.resetFields();
    setRegistervisiable(false);
    setLogininvisiable(true);
  }, [registerform]);
  //退出登录
  const exitlogin = () => {
    if (location.pathname === "/homepage" && location.search) {
      navigate("/homepage");
    }
    dispatch(loginpatch({}));
    dispatch(
      getcollectidar1({
        collectarr: [],
        commentarr: [],
        messagearr: [],
      })
    );
    if (["/edituser", "/write", "/Notice"].includes(location.pathname)) {
      navigate("/");
    }
  };
  //写文章
  const writeessay = () => {
    navigate("/write");
  };
  //获取消息数量
  const getnotreadycountfn = async () => {
    try {
      const re: any = await getnotreadycountapi(user.id);
      setNotreadycount(re.result);
    } catch (e) {
      dispatch(loginpatch({}));
      message.error("身份失效");
    }
  };
  return (
    <div
      className={Headnav.headnavwrap}
      style={
        ani
          ? {
              transform: "translateY(-100%)",
            }
          : { transform: "none" }
      }
    >
      <div className={Headnav.content}>
        <span>こ江桦</span>
        <nav>
          <NavLink to="/homepage">首页</NavLink>
          <NavLink to="/message">留言</NavLink>
          <NavLink to="/lin">友邻</NavLink>
          <NavLink to="/circle">圈子</NavLink>
        </nav>
        <div className="operate">
          <SearchOutlined
            onClick={(e) => {
              navigate("/search");
            }}
          />
          {essaypretheme === "light" ? (
            <CloudOutlined onClick={changetheme} />
          ) : (
            <span className="iconfont icon-weibiaoti-" onClick={changetheme} />
          )}

          {(user as usertype).id ? (
            <>
              {notreadycount > 0 && (
                <div className="messagecount">{notreadycount}</div>
              )}
              <BellOutlined onClick={(e) => navigate("/Notice")} />
              <Dropdown
                overlay={
                  <Menu
                    items={[
                      {
                        label: <div onClick={(e) => writeessay()}>写文章</div>,
                        key: "0",
                      },
                      {
                        label: (
                          <div
                            onClick={(e) => navigate(`/userpage/${user.id}`)}
                          >
                            个人主页
                          </div>
                        ),
                        key: "1",
                      },
                      {
                        label: <div onClick={exitlogin}>退出</div>,
                        key: "2",
                      },
                    ]}
                  />
                }
              >
                <Space>
                  <img
                    style={{ width: 40, height: 40, borderRadius: "50%" }}
                    src={user.avatar}
                    alt=""
                  />
                </Space>
              </Dropdown>
            </>
          ) : (
            <span
              className="login"
              onClick={(e) => {
                setLogininvisiable(true);
              }}
            >
              登录
            </span>
          )}
        </div>
      </div>
      {/* 登录对话框 */}
      <Loginmodel
        loginvisiable={loginvisiable}
        setLogininvisiable={setLogininvisiable}
        toregistermodel={toregistermodel}
        loginform={loginform}
      ></Loginmodel>
      {/* 注册对话框 */}
      <Registermodel
        registevisiable={registevisiable}
        setRegistervisiable={setRegistervisiable}
        tologinmodel={tologinmodel}
        registerform={registerform}
      ></Registermodel>
    </div>
  );
}
